<script lang="ts" setup>
import { ref, reactive, watch } from "vue"
import { Search, Refresh } from "@element-plus/icons-vue"
import { type FormInstance } from "element-plus"
import { formatDateTime } from "@/utils/index"
import { usePagination } from "@/hooks/usePagination"
import { shortcuts } from "@/utils/dateSet"
import { SendingQuery, SendingsmsTpQuery, SendingsmsTpQueryToatl } from "@/api/SendingRecord/index"

const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

// #region 搜索内容
const searchFormRef = ref<FormInstance | null>(null)
const searchData = reactive<any>({
  time: "",
  sendId: "",
  phone: "",
  status: "",
  teamName: ""
})
const defaultTime1: [Date, Date] = [new Date(2000, 1, 1, 0, 0, 0), new Date(2000, 2, 1, 23, 59, 0)]

const resetSearch = () => {
  searchFormRef.value?.resetFields()
  if (paginationData.currentPage === 1) {
    getTableData()
    TpQueryToatl()
    console.log("重置")
  }
  paginationData.currentPage = 1
}
const handleSearch = () => {
  if (paginationData.currentPage === 1) {
    getTableData()
    TpQueryToatl()
    console.log("查询")
  }
  paginationData.currentPage = 1
}
// #endregion

// #region 查找账号
import { useUserListStore } from "@/store/modules/userList"
const UserListArr = ref()
const UserStore = useUserListStore()
UserStore.getUserListFn()
watch(
  [() => UserStore.userListStore],
  (newValue) => {
    UserListArr.value = newValue.flat()
  },
  {
    immediate: true
  }
)
// #endregion

// #region 所有团队
import { useTeamStore } from "@/store/modules/team"
const teamStore = useTeamStore()
const tableDataB = ref<any[]>([])
teamStore.getTeamFn()
watch(
  [() => teamStore.teamListStore],
  (newValue) => {
    tableDataB.value = newValue.flat()
  },
  { immediate: true }
)

// #endregion

//  #region 查看所有信息
const tableData = ref<any>([])
const getTableData = async () => {
  if (!searchData.time) {
    searchData.time = []
  }
  await SendingsmsTpQuery({
    start: new Date(searchData.time[0]).getTime() || "",
    end: new Date(searchData.time[1]).getTime() || "",
    size: paginationData.pageSize,
    page: paginationData.currentPage,
    sendId: searchData.sendId || "",
    phone: searchData.phone || "",
    status: searchData.status || "",
    teamName: searchData.teamName || ""
  }).then((res: any) => {
    tableData.value = res.data.list
    paginationData.total = res.data.total
    // console.log(res, "获取")
  })
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })
// #endregion

// #region 充值的弹出框
// const dialogVisibleSendingRecord = ref(false) // 打开详情框
// const formData = reactive<any>({ data: {} }) // 回显示赋值
// //  充值弹窗
// const SendingRecordadd = () => {
//   dialogVisibleSendingRecord.value = true
//   // 暂时没有金额 虚假字段
//   formData.data.money = ""
// }
// const SendingRecordCZ = () => {
//   SendingAdd(formData.data).then((res: any) => {
//     console.log(res, "充值后的数据")
//     if (res.code == 200) {
//       ElMessage.success(res.data)
//       dialogVisibleSendingRecord.value = false
//       TpQueryToatl()
//     } else {
//       dialogVisibleSendingRecord.value = false
//     }
//   })
// }
// const formRef = ref<FormInstance | null>(null)
// // 清除规则报错信息
// const clearValidate = () => {
//   formRef.value?.clearValidate()
// }
// const resetForm = () => {
//   getTableData()
//   formData.data = {}
//   clearValidate()
// }
// #endregion

// #region 充值记录
const tableWork = ref<any>([])
const dialogVisibleSendingJL = ref(false)
const SendingRecordQuery = () => {
  dialogVisibleSendingJL.value = true
  // 是后端从token拿的id
  SendingQuery({
    page: 1,
    size: 100000
  }).then((res: any) => {
    console.log(res, "日志")
    tableWork.value = res.data.list
    TpQueryToatl()
  })
}
// #endregion

// #region 余额条数
import { useUserStore } from "@/store/modules/user"
const userStore = useUserStore()
const userRows = ref() // 短信余额
const rowsCount = ref() // 短信累计
const TpQueryToatl = () => {
  SendingsmsTpQueryToatl({
    id: userStore.usernameID
  }).then((res: any) => {
    // console.log(res, "条数")
    userRows.value = res.data.userRows
    rowsCount.value = res.data.rowsCount
  })
}
TpQueryToatl()
// #endregion
</script>

<template>
  <div class="app-container">
    <!-- <el-button @click="wxiant">点击</el-button> -->
    <!-- 搜索 -->
    <el-card shadow="never" class="search-wrapper">
      <div style="display: flex">
        <el-form ref="searchFormRef" :inline="true" :model="searchData">
          <el-form-item prop="time" label="发送时间">
            <el-date-picker
              v-model="searchData.time"
              type="datetimerange"
              range-separator="到"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              :shortcuts="shortcuts"
              :default-time="defaultTime1"
            />
          </el-form-item>
          <el-form-item prop="sendId" label="短信ID">
            <el-input v-model.trim="searchData.sendId" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="status" label="短信状态">
            <el-input v-model.trim="searchData.status" placeholder="请输入" />
          </el-form-item>
          <el-form-item prop="phone" label="收信人号码">
            <el-input v-model.trim="searchData.phone" placeholder="请输入" />
          </el-form-item>
          <el-form-item label="发信团队" prop="teamName">
            <el-select v-model="searchData.teamName" clearable filterable placeholder="请选择发信团队">
              <el-option v-for="item in tableDataB" :key="item.id" :label="item.name" :value="item.name" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
            <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
        <div style="margin-right: 20px">
          <div class="boxbutton">
            <!-- <el-button type="primary" @click="SendingRecordadd" round>短信充值</el-button> -->
            <el-button type="primary" @click="SendingRecordQuery" round>充值记录</el-button>
          </div>
          <div>
            <div class="boxtext">
              <el-text type="primary" round>当前账户短信余额：{{ userRows }}条</el-text>
            </div>
            <div class="boxtext">
              <el-text type="primary" round>当前账户累计充值：{{ rowsCount }}条</el-text>
            </div>
          </div>
        </div>
      </div>
    </el-card>
    <!-- 渲染 -->
    <el-card shadow="never">
      <div class="table-wrapper">
        <el-table :data="tableData" ref="tableRef">
          <el-table-column label="发送时间" align="center">
            <template #default="scope">
              {{ formatDateTime(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="sendId" label="短信ID" align="center" />
          <el-table-column prop="tpMsg" label="短信内容" align="center" />
          <el-table-column prop="teamName" label="发信团队" align="center" />
          <el-table-column prop="createBy" label="发信人" align="center" />
          <el-table-column prop="phone" label="收信人号码" align="center" />
          <el-table-column prop="rows" label="计量条数" align="center" />
          <el-table-column prop="status" label="短信状态" />
        </el-table>
      </div>
      <div class="pager-wrapper">
        <el-pagination
          background
          :layout="paginationData.layout"
          :page-sizes="paginationData.pageSizes"
          :total="paginationData.total"
          :page-size="paginationData.pageSize"
          :currentPage="paginationData.currentPage"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    <!-- 充值页面 -->
    <!-- <el-dialog v-model="dialogVisibleSendingRecord" title="短信充值" @close="resetForm" width="30%">
      <el-form ref="formRef" :model="formData.data" label-width="100px" label-position="left">
        <el-form-item prop="id" label="充值账号">
          <el-select v-model="formData.data.id" clearable placeholder="请选择充值账号" style="width: 240px" filterable>
            <el-option v-for="item in UserListArr" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="充值条数" prop="smsRows">
          <el-input v-model="formData.data.smsRows" placeholder="请输入充值条数" style="width: 240px" />
        </el-form-item>
        <div>
          <el-text class="mx-1" type="info">充值规则: 70字内(含70字)计一条,超过70字,按67字/条计费。</el-text>
          <br />
        </div>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="SendingRecordCZ">确定充值</el-button>
        <el-button @click="dialogVisibleSendingRecord = false">取消</el-button>
      </template>
    </el-dialog> -->

    <!-- 短信充值记录 -->
    <el-dialog v-model="dialogVisibleSendingJL" title="短信充值" width="60%">
      <el-scrollbar height="600px">
        <el-table :data="tableWork">
          <el-table-column type="index" label="序号" width="120" align="center">
            <template #default="{ $index }">
              {{ (paginationData.currentPage - 1) * paginationData.pageSize + $index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="time" label="时间" align="center">
            <template #default="scope">
              <text v-if="scope.row.time !== null"> {{ formatDateTime(scope.row.createTime) }}</text>
            </template>
          </el-table-column>
          <el-table-column prop="userId" label="充值人" align="center" />
          <el-table-column prop="rowsChange" label="充值条数" align="center" />
        </el-table>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.search-wrapper {
  margin-bottom: 20px;
}
.pager-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 10px;
}
.boxtext {
  width: 250px;
  margin-top: 10px;
  background-color: #fff;
  border: 1px dashed #79bbff;
  border-radius: 20px;
  text-align: center;
}
.boxbutton {
  display: flex;
  justify-content: space-around;
}
</style>
